package org.megha.blog.example.threads;

import java.util.ArrayList;
import java.util.List;

public class Main {

	public static void main(String args[]) throws InterruptedException{

		ThreadUnsafeCounter unsafeCounter = new ThreadUnsafeCounter();
		ThreadSafeCounter safeCounter = new ThreadSafeCounter();
		CounterIncrementor incrementor =
				new CounterIncrementor(unsafeCounter, safeCounter, 10000);

		List<Thread> threads = new ArrayList<Thread>();
		// start lots of parallel threads that increment the counter(s)
		for (int i = 0; i < 100; i++) {
			Thread thread = new Thread(incrementor);
			thread.start();
			threads.add(thread);
		}

		// wait for all threads to finish
		for (Thread thread: threads) {
			thread.join();
		}

		// count on unsafe counter matches that of safe counter because
		// CounterIncrement increments unsafeCounter in a safe manner
		System.out.println(unsafeCounter.getCount());
		System.out.println(safeCounter.getCount());
	}
}
